<?php
/**
 * Svick a Fast Simple Smart PHP FrameWork
 * Author: Tommy 863758705@qq.com
 * Link: http://svick.tomener.com/
 * Since: 2022
 */

namespace lib\token;


use lib\encrypt\AesEncrypt;
use Svick\Config\Config;

class TokenLib
{
    /**
     * 加密配置
     *
     * @var array
     */
    protected $config = [];

    /**
     * 单例实例
     *
     * @var TokenLib
     */
    protected static $instances;

    /**
     * 构造函数
     *
     * @param $config
     */
    public function __construct($config)
    {
        $this->config = $config;
    }

    /**
     * 单例
     *
     * @param null $config
     * @return TokenLib
     */
    public static function make($config = null): TokenLib
    {
        if (is_null($config)) {
            $config = Config::runtime('encryption.aes');
        } elseif (is_string($config)) {
            $config = Config::runtime($config);
        }

        $name = md5($config['key'] . $config['method']);

        if (!isset(self::$instances[$name])) {
            self::$instances[$name] = new self($config);
        }

        return self::$instances[$name];
    }

    /**
     * 生成Token
     *
     * @param $data
     * @param $expire
     * @return string
     */
    public function create($data, $expire): string
    {
        if (!is_array($data)) {
            $data = [$data];
        }
        $data = json_encode($data, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
        return AesEncrypt::make($this->config)->expire($expire)->encrypt($data);
    }

    /**
     * 验证Token有效性
     *
     * @param $token
     * @return array
     */
    public function validate($token): array
    {
        $ret = AesEncrypt::make($this->config)->decrypt($token);
        if ($ret[0] === 0) {
            $ret[2] = json_decode($ret[2], true);
            if (count($ret[2]) == 1) {
                $ret[2] = $ret[2][0];
            }
        }
        return $ret;
    }
}
